package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

public class Address {

	public static void main(String[] args) {
//		try {
//			test2();
//		} catch (UnknownHostException e) {
//			e.printStackTrace();
//		}
		URLTest();
	}
	
	public static void URLTest(){
		try {
			//URL url = new URL("https", "112.124.119.80", 8080, "/");
			URL url = new URL("http://www.baidu.com:80/index.html");
			System.out.println(url.getHost());
			System.out.println(url.getPath());
			System.out.println(url.getFile());
			System.out.println(url.getPort());
			//参数
			System.out.println(url.getQuery());
			
			//获取资源
			//1.获取资源网络流
//			InputStream is = url.openStream();
//			byte[] flush = new byte[1024];
//			int len = 0;
//			while(-1 != (len = is.read(flush))){
//				System.out.println(new String(flush,0,len));
//			}
//			is.close();
			
			//使用转换流解决乱码问题
			BufferedReader br = new BufferedReader(
					new InputStreamReader(url.openStream(),"utf-8"));
			char[] flush = new char[1024];
			int len = 0;
			while(-1 != (len = br.read(flush))){
				System.out.println(new String(flush,0,len));
			}
			br.close();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void test2() throws UnknownHostException{
		InetSocketAddress socketAddr = new InetSocketAddress("www.163.com",6060);
		socketAddr = new InetSocketAddress(InetAddress.getByName("www.xinlang.com"),6060);
		System.out.println(socketAddr.getHostName());
		System.out.println(socketAddr.getAddress());
	}
	
	public static void test1(){
		try {
			InetAddress address = InetAddress.getLocalHost();
			System.out.println(address.getHostAddress());
			System.out.println(address.getHostName());
			
			address = InetAddress.getByName("www.baidu.com");
			System.out.println(address.getHostAddress());
			System.out.println(address.getHostName());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

}
